﻿using System;
using System.Reflection;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace Ext.Direct.Mvc
{
    internal class DirectMethod
    {
        internal DirectMethod(MethodBase methodInfo) {
            this.Name = methodInfo.Name;
            this.Len = methodInfo.GetParameters().Length;

            // Form methods must be marked with FormHandlerAttribute
            if (methodInfo.GetCustomAttributes(typeof(FormHandlerAttribute), true).Length > 0) {
                this.IsFormHandler = true;
            }
        }

        internal string Name {
            get;
            private set;
        }

        internal int Len {
            get;
            private set;
        }

        internal bool IsFormHandler {
            get;
            private set;
        }

        // Writes JSON representaion of the method to the specified JsonWriter.
        // Used to generate Ext.Direct API
        internal void WriteJson(JsonWriter jsonWriter) {
            jsonWriter.WriteStartObject();
            jsonWriter.WriteProperty("name", this.Name);
            jsonWriter.WriteProperty("len", this.Len);
            if (this.IsFormHandler) {
                jsonWriter.WriteProperty("formHandler", true);
            }
            jsonWriter.WriteEndObject();
        }

        internal static bool IsDirectMethod(MethodInfo methodInfo) {
            // Any controller action is a direct method unless marked with DirectIgnoreAttribute
            bool returnsActionResult = (methodInfo.ReturnType == typeof(ActionResult) || methodInfo.ReturnType.IsSubclassOf(typeof(ActionResult)));
            bool ignore = methodInfo.GetCustomAttributes(typeof(DirectIgnoreAttribute), true).Length > 0;
            return (returnsActionResult && !ignore);
        }
    }
}
